<script lang="ts" setup>
import { reactive, ref, Ref, computed, onMounted } from "vue"
import { useRouter } from "vue-router"
import { useUserStore } from "@/store/modules/user"
import { ElMessage, type FormInstance, type FormRules } from "element-plus"
import { User, Lock } from "@element-plus/icons-vue"
import { type ILoginParams } from "@/api/login/types/login"
import { useFocus } from "./hooks/useFocus"
import logo from "@/assets/images/login-logo.png"
import logoBg from "@/assets/images/login-img.png"
import Modal from "@/components/modal/index.vue"
import { strictCheckPassword, simpleCheckPassword } from "@/utils/index"
import { storeToRefs } from "pinia"
import { removeToken, setToken } from "@/utils/token"
import { editLoginPwdApi, getSystemVersionApi } from "@/api/login/index"

enum USERROLE {
  /** 超级管理员 */
  SUPERADMIN = "1"
}

interface ISetPwd {
  password: string
  confirmPwd: string
}

const loginModalRef: Ref<typeof Modal | null> = ref(null)
const setPasswordForm = reactive<ISetPwd>({
  password: "",
  confirmPwd: ""
})

const userStore = useUserStore()
const { is_signin, userInfo } = storeToRefs(userStore)
const activeName = ref("password")
const router = useRouter()
const { handleBlur, handleFocus } = useFocus()

const loginFormRef = ref<FormInstance | null>(null)
const pwdFormRef = ref<FormInstance | null>(null)
const version = ref<string>("")
const loading = ref(false)

// 登录表单数据
const loginFormData = reactive<ILoginParams>({
  number: "",
  password: ""
})

// 登录表单校验规则
const loginFormRules: FormRules = {
  number: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 16, message: "长度在 6到 16 个字符", trigger: "blur" }
  ]
}

// 检验密码是否相同
const checkSame = (rule: any, value: string, callback: any) => {
  if (!value) {
    rule.message = "请再次输入新密码"
    callback(new Error("请再次输入新密码"))
    return
  }

  if (value !== setPasswordForm.password) {
    rule.message = "新密码不一致"
    callback(new Error("密码不一致"))
  } else {
    callback()
  }
}
const isSuper = computed(() => {
  return userInfo.value.user_role === USERROLE.SUPERADMIN
})

const rules = reactive<FormRules<ISetPwd>>({
  password: [
    { required: true, message: "请输入可更新密码", trigger: "blur" },
    { required: true, trigger: "blur", validator: isSuper.value ? strictCheckPassword : simpleCheckPassword }
  ],

  confirmPwd: [{ required: true, trigger: "blur", validator: checkSame }]
})

/** 登录逻辑 */
const handleLogin = () => {
  loginFormRef.value?.validate(async (valid: boolean, fields) => {
    if (valid) {
      loading.value = true
      await userStore.login(loginFormData)
      loading.value = false

      // 首次登录
      if (!is_signin.value) {
        ;(loginModalRef as Ref<typeof Modal>).value.showModal()
        removeToken()
      } else {
        // 非首次登录
        router.push({ path: "/" })
      }
    } else {
      console.error("表单校验不通过", fields)
    }
  })
}

// 确认修改密码
const handleConfirmPwd = () => {
  pwdFormRef.value?.validate(async (valid) => {
    console.info(valid)
    if (valid) {
      try {
        const params = {
          user_password: setPasswordForm.password
        }
        setToken(userStore.token)
        const res = await editLoginPwdApi(params)
        const { result, return_message } = res
        if (result === 200) {
          // 关闭弹窗
          ;(loginModalRef as Ref<typeof Modal>).value.closeModal()
          ElMessage.success("修改成功")
          userStore.setSignin()
          router.push({ path: "/" })
        } else {
          ElMessage.error(return_message)
        }
      } catch (error) {
        console.info(error)
      }
    }
  })
}

// 获取系统版本
const getVersion = async () => {
  const res = await getSystemVersionApi()
  const { result, data, return_message } = res

  if (result === 200) {
    version.value = data.version
  } else {
    ElMessage.error(return_message)
  }
}

onMounted(() => {
  getVersion()
})
</script>

<template>
  <div class="flex w-full items-center justify-center min-h-full flex-col bg-#e8f1ff">
    <div class="login-container bg-#e8f1ff">
      <div>
        <img w-652px h-544px :src="logoBg" class="-mt-16 -enter-x" />
      </div>

      <div ml-300px class="login-card">
        <div flex items-center justify-center mb-30px mt-100px>
          <img w-58px h-34px :src="logo" mx-15px />
          <span class="text-#4879fb" text-30px>智能输液后台管理系统</span>
        </div>

        <el-tabs v-model="activeName" w-135px pl-50px>
          <el-tab-pane label="账号密码登录" name="password" />
        </el-tabs>

        <div class="content">
          <el-form ref="loginFormRef" :model="loginFormData" :rules="loginFormRules" @keyup.enter="handleLogin">
            <el-form-item prop="number">
              <el-input
                clearable
                v-model.trim="loginFormData.number"
                placeholder="请输入账号"
                type="text"
                tabindex="1"
                :prefix-icon="User"
                size="large"
              />
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                clearable
                v-model.trim="loginFormData.password"
                placeholder="请输入密码"
                type="password"
                tabindex="2"
                :prefix-icon="Lock"
                size="large"
                show-password
                @blur="handleBlur"
                @focus="handleFocus"
              />
            </el-form-item>

            <el-button
              :disabled="!Boolean(loginFormData.number && loginFormData.password)"
              :loading="loading"
              type="primary"
              class="bg-#7fa1fc! my-40px!"
              size="large"
              @click.prevent="handleLogin"
              >登 录</el-button
            >
          </el-form>
        </div>

        <Modal :title-center="true" :show-colse="false" ref="loginModalRef" title="请设置新密码" width="420">
          <template #content>
            <div>
              <el-form
                ref="pwdFormRef"
                :rules="rules"
                :model="setPasswordForm"
                label-width="auto"
                style="max-width: 600px"
              >
                <el-form-item class="mb-30px!" label="密码：" prop="password">
                  <el-input v-model="setPasswordForm.password" show-password placeholder="输入可更新密码" />
                </el-form-item>

                <el-form-item label="确认密码：" prop="confirmPwd">
                  <el-input v-model="setPasswordForm.confirmPwd" show-password placeholder="再次输入新密码" />
                </el-form-item>
              </el-form>

              <span class="text-#B6B6B7">{{
                isSuper
                  ? "长度不得少于8位，由数字、大&小写字母、符号组成（至少4选3）"
                  : "密码长度不得少于6位，由任意数字、字母、符号或其组合组成"
              }}</span>
            </div>
          </template>

          <template #footer>
            <div pr-20px flex justify-center items-center>
              <el-button @click="handleConfirmPwd" type="primary" class="bg-#387af6! w-105px!">确认</el-button>
            </div>
          </template>
        </Modal>
      </div>
    </div>

    <div absolute bottom-10px>
      <span class="text-#9ca3af">版本号：{{ version }}</span>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  min-height: 100%;
  .theme-switch {
    position: fixed;
    top: 5%;
    right: 5%;
    cursor: pointer;
  }
  .login-card {
    width: 480px;
    max-width: 90%;
    border-radius: 10px;
    box-shadow: 0 0 10px #dcdfe6;
    background-color: var(--el-bg-color);
    overflow: hidden;

    .content {
      padding: 10px 50px 50px 50px;
      :deep(.el-input-group__append) {
        padding: 0;
        overflow: hidden;
        .el-image {
          width: 100px;
          height: 40px;
          border-left: 0px;
          user-select: none;
          cursor: pointer;
          text-align: center;
        }
      }
      .el-button {
        width: 100%;
        margin-top: 10px;
      }
    }
  }
}

:deep(.el-dialog) {
  background: #f7f9fb;
  padding-left: 0;
  padding-right: 0;
  padding-top: 0;
  border-radius: 5px;

  .el-dialog__body {
    padding: 20px;
  }
}
</style>
